
#include <lib_include.h>
#include <lib_log.h>
#include <lib_proto/lib_msgbuf.h>
#include <lib_err_code.h>
#include <lib_util.h>
#include <lib_timer.h>

#include <bench_conf.h>

#include "login_base.h"

el::lib_timer_t g_timer;

extern "C" int on_init()
{
	if(el_async::is_parent()){
		DEBUG_LOG("======daemon start======");
	}else{
		DEBUG_LOG("======server start======");
		if (0 != g_login.init()
			|| 0 != g_verify_service.init()){
			return -1;
		}
	}
	return 0;
}

extern "C" int on_fini()
{
	if (el_async::is_parent()) {
		DEBUG_LOG("======daemon done======");
	}else{
		DEBUG_LOG("======server done======");
	}
	return 0;
}

extern "C" void on_events()
{
	if (el_async::is_parent()){
	}else{
		g_timer.handle_timer();
	}
}

extern "C" int on_get_pkg_len(el::lib_tcp_peer_info_t* peer_fd_info,
							  const void* data, uint32_t len)
{
	if (len < el::proto_head_t::get_pkg_len_min_len()){
		return 0;
	}

	el::recv_data_cli_t in(data);
	uint32_t pkg_len = in.get_len();
//	TRACE_LOG("[fd:%d, len:%d, pkg_len:%u]", peer_fd_info->get_fd(), len, pkg_len);
	if (pkg_len < sizeof(el::proto_head_t) || pkg_len > el_async::bench_conf_t::get_instance().get_page_size_max()){
		ERROR_LOG("head len err [len=%u]", pkg_len);
		return -1;
	}

	return pkg_len;
}

extern "C" int on_cli_pkg(const void* data, uint32_t len, el::lib_tcp_peer_info_t* peer_fd_info)
{
	g_login.do_handle_dispatcher(data, len, peer_fd_info);
	return 0;
}

extern "C" void on_srv_pkg(const void* data, uint32_t len, el::lib_tcp_peer_info_t* peer_fd_info)
{
//	TRACE_LOG("[fd:%d, ip:%s, port:%u]", peer_fd_info->get_fd(), peer_fd_info->get_ip_str().c_str(), peer_fd_info->get_port());
	g_verify_service.do_handle_dispatcher(data, len, peer_fd_info);
}

extern "C" void on_cli_conn_closed(int fd)
{
	ERROR_LOG("[fd:%d]", fd);
	g_user_mgr.clear_by_fd(fd);
}

extern "C" void on_svr_conn_closed(int fd)
{
	ERROR_LOG("[fd:%d]", fd);
	g_user_mgr.clear_all();
}

extern "C" void	on_mcast_pkg(const void* data, int len)
{
}

extern "C"  void on_addr_mcast_pkg(uint32_t id, const char* name, const char* ip, uint16_t port, int flag)
{
	ERROR_LOG("id:%u, name:%s, ip:%s, port:%u, flag:%u", id, name, ip, port, flag);
}

extern "C" void on_udp_pkg(int fd, const void* data, int len ,struct sockaddr_in* from, socklen_t fromlen)
{
}

//

